﻿using System;
using System.Data;
using System.ServiceModel;
using System.Windows.Forms;
using System.ComponentModel;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient
{
    public partial class Product : Form
    {
        private DataTable dt;
        private string ambient;
        private WSHttpBinding Binding;
        private EndpointAddress address;

        public Product()
        {
            Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.SendTimeout = TimeSpan.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.ambient = Properties.Settings.Default.CurrentEnv;

            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getCountryList(this.ambient);
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.CuntrysListErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.CuntrysNullListErrorMsg);
            }

            InitializeComponent();
            this.dt = new DataTable();
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Product Report";

            uceCountry.DisplayMember = "dsCountry";
            uceCountry.ValueMember = "idCountry";

            DataTable dtCountry = new DataTable("dtCountryList");
            dtCountry.Columns.Add("idCountry");
            dtCountry.Columns.Add("cdCountry");
            dtCountry.Columns.Add("dsCountry");

            DataSet ds = new DataSet();
            ds.Tables.Add(dtCountry);

            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceCountry.DataSource = dtCountry;
            uceCountry.SelectedIndex = 0;
            xmlSR.Close();
        }

        private void activarControles(bool value)
        {
            loader.Visible = !value;
            ugProduct.Enabled = value;
            ultraGroupBox1.Enabled = value;
        }

        private void bgwSearch_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            DMSServices.DMSServicesClient client = new DMSServices.DMSServicesClient(Binding, address);
            string respuesta = null;
            try
            {
                client.Open();
                respuesta = client.getProductReport(ambient, uceCountry.Value.ToString());
                client.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (respuesta == null)
            {
                throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            }

            dt = new DataTable("dtProduct");
            dt.Columns.Add("cdsku");
            dt.Columns.Add("idstatus");
            dt.Columns.Add("dsproduct");
            dt.Columns.Add("nmclassiflevel1");dt.Columns.Add("nmclassification1");
            dt.Columns.Add("nmclassiflevel2");dt.Columns.Add("nmclassification2");
            dt.Columns.Add("nmclassiflevel3");dt.Columns.Add("nmclassification3");
            dt.Columns.Add("nmclassiflevel4");dt.Columns.Add("nmclassification4");
            dt.Columns.Add("nmclassiflevel5");dt.Columns.Add("nmclassification5");
            dt.Columns.Add("nmclassiflevel6");dt.Columns.Add("nmclassification6");
            dt.Columns.Add("nmclassiflevel7");dt.Columns.Add("nmclassification7");
            dt.Columns.Add("nmclassiflevel8");dt.Columns.Add("nmclassification8");
            dt.Columns.Add("cdunit");
            dt.Columns.Add("nmproduct");
            dt.Columns.Add("flexi1");
            dt.Columns.Add("vlconversionunit");
            dt.Columns.Add("vlConversionKGLT");

            DataSet dataSet = new DataSet("dsProduct");
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwSearch_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugProduct.DataSource = dt;
                activarControles(true);
            }
        }

        private void ubSearch_Click(object sender, EventArgs e)
        {
            activarControles(false);
            bgwSearch.RunWorkerAsync();
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            if (ugProduct.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugProduct, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", this.Text, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void Product_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Product_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgwSearch.IsBusy)
            {
                bgwSearch.CancelAsync();
            }
        }

        private void Product_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void uceCountry_ValueChanged(object sender, EventArgs e)
        {
            dt.Rows.Clear();
            ugProduct.Invalidate();
            ugProduct.Update();
        }

        private void Product_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugProduct_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }
    }
}